<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        // 创建一个构造函数 形参为一个回调
        let MyPromise = function(func) {
                let _this = this
                _this.status = 'pending' // 初始的状态值
                _this.sucValue = undefined //初始的成功的状态值
                _this.errValue = undefined // 初始的失败的状态值
                _this.resolveCallbacks = [] // 缓存成功回调
                _this.rejectCallbacks = [] // 缓存失败回调
                function resolve(value) { //成功的回调
                    if (_this.status === 'pending') {
                        _this.sucValue = value
                        _this.status = 'resolved'
                        _this.resolveCallbacks.forEach(fn => fn());
                    }
                }

                function reject(value) { // 失败的回调
                    if (_this.status === 'pending') {
                        _this.errValue = value
                        _this.status = 'rejected'
                        _this.rejectCallbacks.forEach(fn => fn())
                    }
                }
                func(resolve, reject)
            }
            // 原型创建一个then方法
        MyPromise.prototype.then = function(sucCallback, errCallback) {
            let _this = this
            if (_this.status === 'pending') {
                // 如果还是pending状态缓存存回调
                _this.resolveCallbacks.push(() => sucCallback(_this.sucValue))
                _this.rejectCallbacks.push(() => errCallback(_this.errValue))
            } else if (_this.status === 'resolved') {
                sucCallback(_this.sucValue)
            } else if (_this.status === 'rejected') {
                errCallback(_this.errValue)
            }

        }

        var myPro = new MyPromise(function(resolve, reject) {
            // reject('失败测试')
            setTimeout(() => {
                // reject('失败测试')
                // resolve('成功测试')
            }, 3000);
        })
        myPro.then(suc => {
            console.log(suc)
        }, err => {
            console.log(err)
        })
    </script>
</body>

</html>